package org.september.pisces.excel.service;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.io.FileUtil;
import org.september.core.component.log.LogHelper;
import org.september.core.exception.BusinessException;
import org.september.pisces.excel.entity.ExcelTemplate;
import org.september.pisces.excel.vo.ExcelImage;
import org.september.pisces.filestore.entity.FileStoreItem;
import org.september.pisces.filestore.service.FileStoreManager;
import org.september.pisces.user.permission.service.OperationLogService;
import org.september.smartdao.common.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;

import jakarta.servlet.http.HttpServletResponse;

@Service
public class PiscesExcelService {

    @Value("${hik.oss.pool:}")
    private String poolName;

    protected LogHelper log = LogHelper.getLogger(this.getClass());

    @Autowired
    private BaseService baseService;

    @Autowired
    private FileStoreManager fileStoreManager;

    @Autowired
    private OperationLogService operationLogService;

    public ExcelTemplate addExcelTmpl(String name, byte[] fileData) {
        String[] arr = name.split("\\.");
        String ext = "";
        if (arr.length > 1) {
            ext = "." + arr[arr.length - 1];
        }
        FileStoreItem item = fileStoreManager.save(poolName, fileData, ext, false, 0f);
        ExcelTemplate vo = new ExcelTemplate();
        vo.setName(name);
        vo.setPath(item.getPath());
        vo.setFileUuid(item.getFileUUID());
        baseService.save(vo);
        return vo;
    }

    public void doExport(HttpServletResponse response, String tmplName, List<Map<String, Object>> datas, String downloadFileName) throws Exception {
        ExcelTemplate tpl = getTemplate(tmplName);
        for (Map<String, Object> map : datas) {
            for (String key : map.keySet()) {
                Object val = map.get(key);
                if (val instanceof ExcelImage) {
                    map.put(key, getWriteCellData((ExcelImage) val));
                }
            }
        }
        if (tpl == null) {
            throw new BusinessException("模板 " + tmplName + " 不存在");
        }
        FileStoreItem item = fileStoreManager.getFileItem(tpl.getFileUuid());
        InputStream ins = fileStoreManager.getInputStreamByUUID(item, false);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(downloadFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        EasyExcel.write(response.getOutputStream()).withTemplate(ins).sheet().doFill(datas);
        ins.close();
        response.getOutputStream().close();
    }

    public void doExportSaveDir(String tmplName, List<Map<String, Object>> datas, String savePath) throws Exception {
        ExcelTemplate tpl = getTemplate(tmplName);
        for (Map<String, Object> map : datas) {
            for (String key : map.keySet()) {
                Object val = map.get(key);
                if (val instanceof ExcelImage) {
                    map.put(key, getWriteCellData((ExcelImage) val));
                }
            }
        }
        if (tpl == null) {
            throw new BusinessException("模板 " + tmplName + " 不存在");
        }
        FileStoreItem item = fileStoreManager.getFileItem(tpl.getFileUuid());
        InputStream ins = fileStoreManager.getInputStreamByUUID(item, false);
        EasyExcel.write(FileUtil.touch(new File(savePath))).withTemplate(ins).sheet().doFill(datas);
    }

    public void deleteTemplate(Long tplId) {
        ExcelTemplate po = baseService.getCommonDao().get(ExcelTemplate.class, tplId);
        if (po == null) {
            throw new BusinessException("数据不存在或已删除");
        }
        fileStoreManager.deleteFile(po.getFileUuid());
        baseService.delete(po);
        operationLogService.addLog("删除了excel模板【" + po.getName() + "】");
    }

    public ExcelTemplate getTemplate(String tmplName) {
        ExcelTemplate vo = new ExcelTemplate();
        vo.setDeleteFlag(0);
        vo.setName(tmplName);
        ExcelTemplate po = baseService.getCommonDao().getByExample(vo);
        return po;
    }

    private WriteCellData<Void> getWriteCellData(ExcelImage emg) throws IOException {
        WriteCellData<Void> cell = new WriteCellData<>();
        List<ImageData> imageDataList = new ArrayList<>();
        ImageData img = new ImageData();
        img.setImage(emg.getDatas());
        imageDataList.add(img);
        cell.setImageDataList(imageDataList);
        return cell;
    }
}
